#include "../include/net_connection.h"

// 获取服务端网络地址
int get_valid_str(char *input, char *str) {
    char *p;
      char s[] = {' ', '\n'};
      p = strtok(input, s);
      p = strtok(NULL, s);
      p = strtok(NULL, s);
      strcpy(str, p);
      return 0;

}

int get_server_conf(char *conf_file, char *ip, char *port, int *pworkernum) {
    FILE *pconf = fopen(conf_file, "r");
      ERROR_CHECK(pconf, NULL, "open conf file failed");
      char buf[128] = {0};
      fgets(buf, sizeof(buf), pconf);
      get_valid_str(buf, ip);
      bzero(buf, sizeof(buf));
      fgets(buf, sizeof(buf), pconf);
      get_valid_str(buf, port);
      bzero(buf, sizeof(buf));
      fgets(buf, sizeof(buf), pconf);
      char num[10] = {0};
      get_valid_str(buf, num);
      *pworkernum = atoi(num);
      fclose(pconf);
      return 0;

}

// 建立tcp连接
int tcp_init(char *ip, char *port) {
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(sockfd, -1, "server socket");
    int reuse = 1;
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
    // addr
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(ip);
    addr.sin_port = htons(atoi(port));
    int ret1 = bind(sockfd, (struct sockaddr*)&addr, sizeof(addr));
    ERROR_CHECK(ret1, -1, "server bind");
    int ret2 = listen(sockfd, 20);
    ERROR_CHECK(ret2, -1, "server listen");
    return sockfd;
}

// epoll监听网络连接
int epoll_add(int epfd, int fd) {
    struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.fd = fd;
    epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev);
    return 0;
}

int epoll_del(int epfd, int fd) {
    epoll_ctl(epfd, EPOLL_CTL_DEL, fd, NULL);
    return 0;
}

